/*
 * CS_REQ_DELETE_SLOT.cpp
 *
 *  Created on: 2013. 8. 20.
 *      Author: the2
 */


#include "../../User.h"
#include "world.h"

namespace ProjectZ { namespace NCommand { namespace NWorld {

void SendAckFail(User * pUser, int8_t slot_number)
{
	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
	pAck->Write2(ACK_UNKNOWN_ERROR);
	pAck->Write1(slot_number);
	pAck->MakePacket(CMD_SC_REQ_DELETE_SLOT);

	pUser->Send(pAck);
}

void CS_REQ_DELETE_SLOT::OnExecute(User * pUser, ::Network::Packet * pPacket)
{
	PREPARE_PACKET;

	uint8_t slot_number = 0;
	*pPacket >> slot_number;

	DEBUGLOG("CS_REQ_DELETE_SLOT slot number : %d mainslot : %d GID : %d",
			slot_number, pUser->GetUserInfo().main_slot_index, pUser->GetUserSeq());

	if (false == pUser->GetUserInfo().array_Slot[slot_number].open || false == pUser->GetUserInfo().array_Slot[slot_number].makeCharacter )
	{
		SendAckFail(pUser, slot_number);
		return;
	}

	if (slot_number == pUser->GetUserInfo().main_slot_index)
	{
		SendAckFail(pUser, slot_number);
		return;
	}

	::Database::Command::Auto clsAuto(::Database::GETCOMMANDPOOL());
	clsAuto->SetQueryType(::Database::Command::S_PROCEDURE);
	clsAuto->MakeQuery("call sp_delete_info_character(%d, %d)", pUser->GetCharacterInfoFromIndex(slot_number).characterseq, pUser->GetUserSeq());
	DEBUGLOG("CS_REQ_DELETE_SLOT QUERY : %s", clsAuto->GetQueryString());
	if (false == ::Database::GETSESSION()->SyncExecute(1, clsAuto))
	{
		DEBUGLOG("CS_REQ_DELETE_SLOT false == ::Database::GETSESSION()->SyncExecute(1, clsAuto)");
		SendAckFail(pUser, slot_number);
		return;
	}

	if( clsAuto->GetErrorIdx() != 0 )
	{
		DEBUGLOG("CS_REQ_DELETE_SLOT clsAuto->GetErrorIdx() != 0");
		SendAckFail(pUser, slot_number);
		return;
	}

	pUser->GetUserInfo().array_Slot[slot_number].open = true;
	pUser->GetUserInfo().array_Slot[slot_number].character_seq = 0;
	pUser->GetUserInfo().array_Slot[slot_number].makeCharacter = false;

	//ProjectZ::FlushUserInfoSyn(pUser, true);

	::Network::Packet * pAck = ::Network::GETPACKETPOOL()->SEND_NEW();
	pAck->Write2(ACK_OK);
	pAck->Write1(slot_number);
	pAck->MakePacket(CMD_SC_REQ_DELETE_SLOT);

	pUser->Send(pAck);
}

} /*NWorld*/ } /*NCommand*/ } /*ProjectZ*/


